﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Collections;
using System.Text;
using System.Reflection;
using System.Web;
using System.Globalization;


namespace dpruna.SharePoint
{
    public partial class ExtendedLookupFieldEditor : UserControl, IFieldEditor
    {
        #region Constants
        private int TxtFielTitledMaxLength = 255;
        #endregion

        #region Fields
        private ExtendedLookup fldLookup;
        private static ArrayList countRelatedLookups;
        public ExtendedLookupRelationshipsEditor LookupRelationshipsEditor;
        public ExtendedLookupCustomProperties ExtentedLookupCustomProps;
        private SPList list;
        private SPWeb web;
        private SPContentType contentType;
        private bool ctFetched = false;
        private string fieldTitle = String.Empty;
        #endregion

        #region Properties
        internal bool CreateBusinessDataLookupFieldInstead
        {
            get
            {
                bool flag = false;
                if (this.DropdownSelectedLookupList.HasExternalDataSource)
                {
                    flag = true;
                }
                return flag;
            }
        }

        public bool DisplayAsNewSection
        {
            get
            {
                return true;
            }
        }

        private SPList DropdownSelectedLookupList
        {
            get
            {
                SPList list = null;
                if (this.DdlLookupFieldTargetList.SelectedIndex >= 0)
                {
                    Guid guid = new Guid(this.DdlLookupFieldTargetList.SelectedValue);
                    list = SPContext.Current.Web.Lists[guid];
                }
                return list;
            }
        }

        protected Guid OwnerListId
        {
            get
            {
                string str = base.Request.QueryString.Get("List");
                if (!string.IsNullOrEmpty(str))
                {
                    return new Guid(str);
                }
                return Guid.Empty;
            }
        }

        protected SPWeb Web
        {
            get 
            {
                if (web == null)
                    web = SPControl.GetContextWeb(this.Context);
                return web;
            }
        }

        protected SPList List
        {
            get
            {
                Guid guid;
                if ((this.list == null) && Helpers.TryParseGuid(HttpContext.Current.Request.QueryString.Get("List"), out guid))
                {
                    this.list = Web.Lists.GetList(guid, true);
                }
                return this.list;
            }
        }

        protected SPContentType ContentType
        {
            get
            {
                if (!this.ctFetched)
                {
                    this.ctFetched = true;
                    string ctString = this.Request["ctype"];
                    if (!String.IsNullOrEmpty(ctString))
                    {
                        SPContentTypeId id = new SPContentTypeId(ctString);
                        this.contentType = this.Web.ContentTypes[id];
                    }
                }
                return this.contentType;
            }
        }
        #endregion

        #region Construction
        public ExtendedLookupFieldEditor() { }
        static ExtendedLookupFieldEditor()
        {
            countRelatedLookups = new ArrayList();
        }
        #endregion

        #region Public & Internal Methods
        internal NameValueCollection GetSelectedDependentLookupNames()
        {
            NameValueCollection values = new NameValueCollection();
            foreach (ListItem item in this.CbxlDependentLookupFields.Items)
            {
                if (item.Selected)
                {
                    values.Add(item.Value, item.Text);
                }
            }
            return values;
        }
        public void InitializeWithField(SPField field)
        {
            this.fldLookup = field as ExtendedLookup;
            this.DdlLookupFieldTargetField.Attributes["onchange"] = "javascript:DisableDependentCountRelatedLookup()";
            string str = "var cbx = document.getElementById('" + this.cbxAllowMultiValue.ClientID + "');if (cbx != null) ChangeRIAndUniquenessDependingOnMultiVal(cbx.checked);";
            if (!this.Page.IsPostBack)
            {
                SPWeb contextWeb = SPControl.GetContextWeb(this.Context);
                SPList lookupTolist = null;
                if (field == null)
                {
                    this.DdlLookupFieldTargetList.Visible = true;
                    this.ifcLabelDependentLookupFields.Visible = true;
                    this.PopulateTargetLists();
                    if (this.DdlLookupFieldTargetList.SelectedIndex >= 0)
                    {
                        if (this.DdlLookupFieldTargetList.SelectedValue == "UserInfo")
                        {
                            lookupTolist = contextWeb.SiteUserInfoList;
                        }
                        else
                        {
                            lookupTolist = this.DropdownSelectedLookupList;
                        }
                        PopulateShowFieldDropDown(this.DdlLookupFieldTargetField, lookupTolist, this.OwnerListId, "Title");
                        PopulateShowFieldDropDown(this.CbxlDependentLookupFields, lookupTolist, this.OwnerListId, "");
                        this.cbxAllowMultiValue.Checked = false;
                        this.cbxAllowMultiValue.Attributes["onclick"] = "UpdateDocLibWarning(); " + str;
                        this.cbxUnlimitedLengthInDocLib.Checked = false;
                    }
                }
                else
                {
                    this.LabelLookupFieldTargetListTitle.Visible = true;
                    ExtendedLookup primaryLookupField = (ExtendedLookup)field;
                    string lookupList = primaryLookupField.LookupList;
                    string lookupField = primaryLookupField.LookupField;
                    SPList list2 = null;
                    if (primaryLookupField != null)
                    {
                        list2 = GetLookupList(SPControl.GetContextWeb(this.Context), primaryLookupField.LookupList, new Guid?(primaryLookupField.LookupWebId));
                    }
                    if (list2 != null)
                    {
                        SPField fieldByInternalName = list2.Fields.GetFieldByInternalName(lookupField, false);
                        if (fieldByInternalName != null)
                        {
                            lookupField = fieldByInternalName.Title;
                        }
                    }
                    lookupTolist = list2;
                    if (lookupTolist == null)
                    {
                        this.LabelLookupFieldTargetListTitle.Text = SPHttpUtility.HtmlEncode(lookupList);
                        this.LabelLookupFieldTargetListTitle.Visible = false;
                        this.LabelLookupFieldTargetField.Text = SPHttpUtility.HtmlEncode(lookupField);
                        this.LabelLookupFieldTargetField.Visible = true;
                        this.DdlLookupFieldTargetField.Visible = false;
                        this.ifcLabelDependentLookupFields.Visible = false;
                        this.cbxAllowMultiValue.Enabled = false;
                        this.cbxUnlimitedLengthInDocLib.Enabled = false;
                    }
                    else
                    {
                        this.LabelLookupFieldTargetListTitle.Text = SPHttpUtility.HtmlEncode(lookupTolist.Title);
                        if (!primaryLookupField.IsDependentLookup)
                        {
                            PopulateShowFieldDropDown(this.DdlLookupFieldTargetField, lookupTolist, this.OwnerListId, primaryLookupField.LookupField);
                            PopulateShowFieldDropDown(this.CbxlDependentLookupFields, lookupTolist, this.OwnerListId, null);
                            this.SetSelectedDependentLookups(GetDependentLookupShowFields(primaryLookupField));
                            this.cbxAllowMultiValue.Enabled = !primaryLookupField.CountRelated;
                        }
                        else
                        {
                            this.LabelLookupFieldTargetField.Text = SPHttpUtility.HtmlEncode(lookupField);
                            this.LabelLookupFieldTargetField.Visible = true;
                            this.DdlLookupFieldTargetField.Visible = false;
                            this.ifcLabelDependentLookupFields.Visible = false;
                            this.cbxAllowMultiValue.Visible = false;
                            this.cbxUnlimitedLengthInDocLib.Visible = false;
                        }
                    }
                    this.cbxAllowMultiValue.Checked = primaryLookupField.AllowMultipleValues;
                    this.cbxUnlimitedLengthInDocLib.Checked = primaryLookupField.UnlimitedLengthInDocumentLibrary;
                    if (primaryLookupField.CountRelated)
                    {
                        this.ifcLabelDependentLookupFields.Visible = false;
                        this.cbxAllowMultiValue.Enabled = false;
                        this.cbxUnlimitedLengthInDocLib.Enabled = false;
                    }
                }
                bool flag = (lookupTolist != null) && lookupTolist.HasExternalDataSource;
                this.LookupRelationshipsEditor.IsHidden = flag;
                if (this.cbxAllowMultiValue.Visible)
                {
                    this.cbxAllowMultiValue.Visible = !flag;
                }
                if (SPContext.Current.List != null)
                {
                    this.SpanDocLibWarning.Visible = SPContext.Current.List.BaseType == SPBaseType.DocumentLibrary;
                    this.SpanLengthWarning.Visible = SPContext.Current.List.BaseType == SPBaseType.DocumentLibrary;
                    this.cbxUnlimitedLengthInDocLib.Visible = SPContext.Current.List.BaseType == SPBaseType.DocumentLibrary;
                }
                this.DisableDependentLookupCheckBoxes();
            }
            this.LookupRelationshipsEditor.InitializeWithField(this.fldLookup, this.cbxAllowMultiValue.ClientID, false);
            this.ExtentedLookupCustomProps.InitializeWithField(this.fldLookup, this.cbxAllowMultiValue.ClientID, false);
        }
        public void OnSaveChange(SPField field, bool bNewField)
        {
            ExtendedLookup lookupField = field as ExtendedLookup;
            fieldTitle = field.Title;
            if (lookupField == null)
            {
                SPBusinessDataField bdfld = (SPBusinessDataField)field;
                this.ConfigureBusinessDataLookupField(bdfld);
            }
            else
            {
                SPWeb contextWeb = SPControl.GetContextWeb(this.Context);
                if (bNewField)
                {
                    lookupField.LookupList = this.DdlLookupFieldTargetList.SelectedValue;
                    SPFieldCollection fields = field.GetPrivatePropertyValue<SPFieldCollection>("Fields");
                    if (((fields == null) || (fields.List == null)) || (fields.Web.ID != contextWeb.ID))
                    {
                        lookupField.LookupWebId = contextWeb.ID;
                    }
                    if (!string.IsNullOrEmpty(this.DdlLookupFieldTargetField.SelectedValue))
                    {
                        lookupField.LookupField = this.DdlLookupFieldTargetField.SelectedValue;
                    }
                }
                else if (!string.IsNullOrEmpty(this.DdlLookupFieldTargetField.SelectedValue))
                {
                    lookupField.LookupField = this.DdlLookupFieldTargetField.SelectedValue;
                }
                lookupField.AllowMultipleValues = this.cbxAllowMultiValue.Checked;
                lookupField.UnlimitedLengthInDocumentLibrary = this.cbxUnlimitedLengthInDocLib.Checked;
                if ((!string.IsNullOrEmpty(lookupField.LookupList) && !string.IsNullOrEmpty(lookupField.LookupField)) && ((lookupField.LookupWebId == contextWeb.ID) && Helpers.IsGuid(lookupField.LookupList)))
                {
                    Guid uniqueID = new Guid(lookupField.LookupList);
                    SPList listById = Helpers.GetListById(contextWeb, uniqueID, false);
                    if (listById == null)
                    {
                        throw new SPException(SPResource.GetString("LookupListDeleted", new object[0]));
                    }
                    SPField fieldByInternalName = listById.Fields.GetFieldByInternalName(lookupField.LookupField);
                    lookupField.CountRelated = ShouldBeCountRelated(fieldByInternalName, this.OwnerListId);
                    if (lookupField.CountRelated)
                    {
                        lookupField.AllowMultipleValues = false;
                    }
                }
                else
                {
                    lookupField.CountRelated = false;
                }
                this.LookupRelationshipsEditor.OnSaveChange(lookupField);
                this.ExtentedLookupCustomProps.OnSaveChange(lookupField);
            }
        }
        #endregion

        #region Private Methods
        private string GetResourceString(string strId, params object[] values)
        {
            string format = HttpContext.GetGlobalResourceObject("wss", strId, CultureInfo.CurrentUICulture) as string;
            return Helpers.SubstituteArgumentValues(format, values);
        }
        private void SetSelectedDependentLookups(List<string> showFieldNames)
        {
            if ((showFieldNames != null) && (showFieldNames.Count != 0))
            {
                foreach (ListItem item in this.CbxlDependentLookupFields.Items)
                {
                    if (showFieldNames.Contains(item.Value))
                    {
                        item.Selected = true;
                    }
                }
            }
        }
        private void PopulateTargetLists()
        {
            foreach (SPList list in SPControl.GetContextWeb(this.Context).Lists)
            {
                if (!list.Hidden && !string.IsNullOrEmpty(list.Title))
                {
                    ListItem item = new ListItem();
                    item.Value = list.ID.ToString("B");
                    item.Text = list.Title;
                    this.DdlLookupFieldTargetList.Items.Add(item);
                }
            }
        }
        private void DisableDependentLookupCheckBoxes()
        {
            if ((this.DdlLookupFieldTargetField != null) && (this.DdlLookupFieldTargetField.Items.Count > 0))
            {
                int selectedIndex = this.DdlLookupFieldTargetField.SelectedIndex;
                string item = this.DdlLookupFieldTargetField.Items[selectedIndex].Value;
                if (item == null)
                {
                    item = this.DdlLookupFieldTargetField.Items[0].Value;
                }
                if (countRelatedLookups.Contains(item))
                {
                    if (this.CbxlDependentLookupFields.Visible)
                    {
                        this.CbxlDependentLookupFields.Enabled = false;
                    }
                    if (this.cbxAllowMultiValue.Visible)
                    {
                        this.cbxAllowMultiValue.Enabled = false;
                    }
                    if (this.cbxUnlimitedLengthInDocLib.Visible)
                    {
                        this.cbxUnlimitedLengthInDocLib.Enabled = false;
                    }
                }
                else
                {
                    if (this.CbxlDependentLookupFields.Visible)
                    {
                        this.CbxlDependentLookupFields.Enabled = true;
                    }
                    if (this.cbxAllowMultiValue.Visible)
                    {
                        this.cbxAllowMultiValue.Enabled = true;
                    }
                    if (this.cbxUnlimitedLengthInDocLib.Visible)
                    {
                        this.cbxUnlimitedLengthInDocLib.Enabled = true;
                    }
                }
            }
        }
        private void ConfigureBusinessDataLookupField(SPBusinessDataField bdfld)
        {
            SPListDataSource dataSource = this.DropdownSelectedLookupList.DataSource;
            if (dataSource != null)
            {
                bdfld.SystemInstanceName = dataSource.GetPrivatePropertyValue<string>("LobSystemInstanceName");
                bdfld.EntityName = dataSource.GetPrivatePropertyValue<string>("EntityName");
                bdfld.EntityNamespace = dataSource.GetPrivatePropertyValue<string>("EntityNamespace");
                bdfld.BdcFieldName = this.DdlLookupFieldTargetField.SelectedValue;
                NameValueCollection selectedDependentLookupNames = this.GetSelectedDependentLookupNames();
                ArrayList list2 = new ArrayList();
                foreach (string str in selectedDependentLookupNames.Keys)
                {
                    list2.Add(str);
                }
                bdfld.SetSecondaryFieldsNames((string[])list2.ToArray(typeof(string)));
                bdfld.HasActions = true;
            }
        }
        private void UpdateDependentLookups(SPField flfField)
        {
            bool pushDownYes = true;
            ExtendedLookup field = flfField as ExtendedLookup;
            string[] strArray = field.GetDependentLookupInternalNames().ToArray();
            NameValueCollection selectedDependentLookupNames = GetSelectedDependentLookupNames();
            for (int i = 0; i < strArray.Length; i++)
            {
                string strName = strArray[i];
                SPFieldCollection fields = field.GetPrivatePropertyValue<SPFieldCollection>("Fields");
                SPFieldLookup fieldByInternalName = (SPFieldLookup)fields.GetFieldByInternalName(strName, false);
                if ((fieldByInternalName != null) && fieldByInternalName.IsDependentLookup)
                {
                    if (selectedDependentLookupNames.Get(fieldByInternalName.LookupField) == null)
                    {
                        fields.Delete(strName);
                    }
                    else
                    {
                        if (!fieldByInternalName.Sealed)
                        {
                            fieldByInternalName.Group = field.Group;
                            if (SPControl.GetContextWeb(this.Context).RegionalSettings.IsRightToLeft)
                            {
                                fieldByInternalName.Direction = field.Direction;
                            }
                            fieldByInternalName.AllowMultipleValues = field.AllowMultipleValues;
                            fieldByInternalName.UnlimitedLengthInDocumentLibrary = field.UnlimitedLengthInDocumentLibrary;
                        }
                        if (this.List == null && pushDownYes) // && this.RadPushDownYes.Checked
                            fieldByInternalName.PushChangesToLists = true;

                        fieldByInternalName.Update();
                        if (((this.List != null) && this.List.AllowContentTypes) && !this.List.ContentTypesEnabled)
                        {
                            SPContentType type = this.List.ContentTypes[0];
                            SPFieldLink link = null;
                            try
                            {
                                link = type.FieldLinks[fieldByInternalName.InternalName];
                            }
                            catch (ArgumentException)
                            {
                            }
                            if (link != null)
                            {
                                link.Required = fieldByInternalName.Required;
                                type.Update();
                            }
                        }
                        selectedDependentLookupNames.Remove(fieldByInternalName.LookupField);
                    }
                }
            }
            if (selectedDependentLookupNames.Count != 0)
            {
                ExtendedLookup lookup3 = field as ExtendedLookup;
                bool bAddToDefaultView = false;
                SPList parentList = lookup3.ParentList;
                if (parentList != null)
                {
                    SPView defaultView = parentList.DefaultView;
                    if (defaultView != null)
                    {
                        SPViewFieldCollection viewFields = defaultView.ViewFields;
                        if ((viewFields != null) && viewFields.Exists(lookup3.InternalName))
                        {
                            bAddToDefaultView = true;
                        }
                    }
                }
                this.CreateDependentLookups(field, selectedDependentLookupNames, bAddToDefaultView, pushDownYes, false);
            }
        }
        private void CreateDependentLookups(ExtendedLookup spPrimaryField, NameValueCollection htSelectedItems, bool bAddToDefaultView, bool bPushChangesToLists, bool bAddToAllContentTypes)
        {
            if ((spPrimaryField == null) || (htSelectedItems == null))
            {
                throw new ArgumentNullException();
            }
            if (spPrimaryField.IsDependentLookup)
            {
                throw new SPException(SPResource.GetString("InvalidPrimaryLookup", new object[0]));
            }
            SPFieldCollection fields = spPrimaryField.GetPrivatePropertyValue<SPFieldCollection>("Fields");
            SPAddFieldOptions op = SPAddFieldOptions.Default;
            if (this.List != null)
            {
                bool flag;
                if (this.List.BaseTemplate == SPListTemplateType.Survey)
                {
                    flag = false;
                }
                else
                {
                    flag = true;
                }
                if (!flag)
                {
                    op = SPAddFieldOptions.AddToNoContentType;
                }
                else if (!this.List.ContentTypesEnabled)
                {
                    op = SPAddFieldOptions.AddToDefaultContentType;
                }
                else if (bAddToAllContentTypes)
                {
                    op = SPAddFieldOptions.AddToAllContentTypes;
                }
                else
                {
                    op = SPAddFieldOptions.AddToNoContentType;
                }
            }
            foreach (string str in htSelectedItems.AllKeys)
            {
                string str2 = htSelectedItems.Get(str);
                if (!string.IsNullOrEmpty(str2))
                {
                    str2 = SPHttpUtility.HtmlDecode(str2, true);
                }
                string displayName = spPrimaryField.Title + this.GetResourceString("fldedit_dependentcolumns_nameprefix", new object[0]) + str2;
                //
                // TODO: get this recusive by searching all parents of this control
                //
                if (displayName.Length > TxtFielTitledMaxLength)
                {
                    displayName = displayName.Substring(0, TxtFielTitledMaxLength);
                }
                SPFieldLookup field = (SPFieldLookup)fields.CreateNewField("Lookup", displayName);
                if (field == null)
                {
                    throw new SPException(SPResource.GetString("CannotCreateFieldOfGivenType", new object[] { "Lookup" }));
                }
                field.LookupList = spPrimaryField.LookupList;
                field.LookupWebId = spPrimaryField.LookupWebId;
                field.LookupField = str;
                field.PrimaryFieldId = spPrimaryField.Id.ToString();
                field.ReadOnlyField = true;
                field.AllowMultipleValues = spPrimaryField.AllowMultipleValues;
                field.UnlimitedLengthInDocumentLibrary = spPrimaryField.UnlimitedLengthInDocumentLibrary;
                if (this.Web.RegionalSettings.IsRightToLeft)
                {
                    field.Direction = spPrimaryField.Direction;
                }
                if (this.List == null)
                {
                    field.Group = spPrimaryField.Group;
                    string strName = fields.Add(field);
                    if (this.ContentType != null)
                    {
                        this.ContentType.FieldLinks.Add(new SPFieldLink(fields.GetFieldByInternalName(strName)));
                        this.ContentType.Update(bPushChangesToLists);
                    }
                }
                else
                {
                    fields.AddFieldAsXml(field.SchemaXml, bAddToDefaultView, op);
                }
            }
        }
        #endregion

        #region Protected Methods
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            StringBuilder builder = new StringBuilder();
            if (countRelatedLookups.Count > 0)
            {
                for (int i = 0; i < countRelatedLookups.Count; i++)
                {
                    if (i > 0)
                    {
                        builder.Append(',');
                    }
                    builder.Append('\'');
                    builder.Append(SPHttpUtility.EcmaScriptStringLiteralEncode((string)countRelatedLookups[i]));
                    builder.Append('\'');
                }
                this.Page.ClientScript.RegisterArrayDeclaration("g_CtRelatedLookupFieldName", builder.ToString());
            }
        }
        protected override void OnUnload(EventArgs e)
        {
            //
            // HACK: in order to run the code after the parent page OK event handler code logic
            //
            // if OK button of parent was clicked then save also the dependent lookups fields
            string eventTarget = HttpContext.Current.Request.Form["__EVENTTARGET"];
            string okButtonClicked = HttpContext.Current.Request.Form["okButtonClicked"];
            if (!String.IsNullOrEmpty(eventTarget) && eventTarget.Contains("onetidSaveItem") &&
                !String.IsNullOrEmpty(okButtonClicked) && bool.TrueString.ToLower().Equals(okButtonClicked.ToLower()))
            {
                try
                {
                    // if new field then get it coz it was created in parent page ok button event handler
                    if (this.fldLookup == null && !String.IsNullOrEmpty(fieldTitle))
                        this.fldLookup = (ExtendedLookup)List.Fields[fieldTitle];

                    UpdateDependentLookups(this.fldLookup);
                }
                catch (Exception ex)
                {
                    SPULSTraceListener traceListener = new SPULSTraceListener();
                    traceListener.WriteLine(ex, "Exception");
                }
            }
            base.OnUnload(e);
        }
        #endregion
        
        #region Static Methods
        internal static bool ShouldBeCountRelated(SPField field, Guid ownerListId)
        {
            bool flag = false;
            if (((field != null) && (field.Type == SPFieldType.Lookup)) && (!(field as SPFieldLookup).IsDependentLookup && (ownerListId != Guid.Empty)))
            {
                SPFieldLookup lookup = (SPFieldLookup)field;
                string lookupList = lookup.LookupList;
                SPFieldCollection fields = field.GetPrivatePropertyValue<SPFieldCollection>("Fields");
                Guid guid = (fields.List != null) ? fields.List.ID : Guid.Empty;
                if (Helpers.IsGuid(lookupList))
                {
                    Guid guid2 = new Guid(lookupList);
                    flag = (((guid != ownerListId) || (guid == Guid.Empty)) && ((guid2 == ownerListId) && !lookup.CountRelated)) && !lookup.AllowMultipleValues;
                }
            }
            return flag;
        }
        internal static void PopulateShowFieldDropDown(ListControl showField, SPList lookupTolist, Guid OwnerListId, string strSelectedField)
        {
            PopulateShowFieldDropDown(showField, lookupTolist, OwnerListId, strSelectedField, null);
        }
        internal static void PopulateShowFieldDropDown(ListControl showField, SPList lookupToList, Guid ownerListId, string strSelectedField, string[] excludedShowFields)
        {
            showField.Items.Clear();
            foreach (SPField field in lookupToList.Fields)
            {
                if (field.Hidden || ((excludedShowFields != null) && (Array.IndexOf<string>(excludedShowFields, field.InternalName) >= 0)))
                {
                    continue;
                }
                if (lookupToList.HasExternalDataSource)
                {
                    if (!field.InternalName.StartsWith("bdil", StringComparison.Ordinal) && (field.InternalName != "BdcIdentity"))
                    {
                        AddFieldToDropDown(showField, field, strSelectedField, null);
                    }
                    continue;
                }
                if (((((field.Type == SPFieldType.Counter) || (field.Type == SPFieldType.Text)) || ((field.Type == SPFieldType.Number) || (field.Type == SPFieldType.DateTime))) || ((field.Type == SPFieldType.Computed) && ((SPFieldComputed)field).EnableLookup)) || ((field.Type == SPFieldType.Calculated) && (((SPFieldCalculated)field).OutputType == SPFieldType.Text)))
                {
                    AddFieldToDropDown(showField, field, strSelectedField, null);
                    continue;
                }
                if ((ShouldBeCountRelated(field, ownerListId) && (!(field is SPFieldLookup) || string.IsNullOrEmpty((field as SPFieldLookup).PrimaryFieldId))) && !(showField is CheckBoxList))
                {
                    AddFieldToDropDown(showField, field, strSelectedField, SPResource.GetString("LookupCountRelatedTag", new object[0]));
                    countRelatedLookups.Add(field.InternalName);
                }
            }
        }
        internal static List<string> GetDependentLookupShowFields(ExtendedLookup primaryLookupField)
        {
            if ((primaryLookupField == null) || primaryLookupField.IsDependentLookup)
            {
                throw new ArgumentNullException();
            }
            List<string> list = new List<string>();
            SPFieldCollection fields = primaryLookupField.GetPrivatePropertyValue<SPFieldCollection>("Fields");
            foreach (SPField field in fields)
            {
                SPFieldLookup lookup = field as SPFieldLookup;
                if (((lookup != null) && lookup.IsDependentLookup) && (Helpers.IsGuid(lookup.PrimaryFieldId) && (new Guid(lookup.PrimaryFieldId) == primaryLookupField.Id)))
                {
                    list.Add(lookup.LookupField);
                }
            }
            return list;
        }
        internal static SPList GetLookupList(SPWeb web, string strLookupList, Guid? lookupWebId)
        {
            SPList list = null;
            if (string.IsNullOrEmpty(strLookupList))
            {
                return null;
            }
            if (strLookupList == "UserInfo")
            {
                return web.SiteUserInfoList;
            }
            Guid empty = Guid.Empty;
            try
            {
                empty = new Guid(strLookupList);
                if (lookupWebId.HasValue && (web.ID != lookupWebId.Value))
                {
                    SPWeb web2 = null;
                    try
                    {
                        try
                        {
                            web2 = web.Site.OpenWeb(lookupWebId.Value);
                            list = web2.Lists[empty];
                        }
                        catch (FileNotFoundException)
                        {
                        }
                        return list;
                    }
                    finally
                    {
                        if (web2 != null)
                        {
                            web2.Close();
                        }
                    }
                }
                list = web.Lists[empty];
            }
            catch (FormatException)
            {
            }
            catch (SPException)
            {
            }
            return list;
        }
        internal static void AddFieldToDropDown(ListControl showField, SPField field, string strSelectedField, string extraText)
        {
            ListItem item = new ListItem();
            item.Text = field.Title + " " + field.AuthoringInfo + " ";
            if (!string.IsNullOrEmpty(extraText))
            {
                item.Text = item.Text + extraText;
            }
            item.Text = item.Text.Trim();
            if (showField is CheckBoxList)
            {
                item.Text = SPHttpUtility.HtmlEncode(item.Text);
            }
            item.Value = field.InternalName;
            if (field.InternalName == strSelectedField)
            {
                item.Selected = true;
            }
            showField.Items.Add(item);
        }
        #endregion

        #region Registered Events
        protected void DdlLookupFieldTargetField_Changed(object sender, EventArgs e)
        {
            SPWeb contextWeb = SPControl.GetContextWeb(this.Context);
            string selectedValue = this.DdlLookupFieldTargetList.SelectedValue;
            Guid empty = Guid.Empty;
            SPList list = null;
            if (string.IsNullOrEmpty(selectedValue))
            {
                list = GetLookupList(contextWeb, selectedValue, null);
            }
            else
            {
                empty = new Guid(selectedValue);
                list = contextWeb.Lists[empty];
            }
            if (list != null)
            {
                BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic;
                ExtendedLookup fieldByInternalName = list.Fields.InvokeMethod<ExtendedLookup>("GetFieldByInternalName", bindingFlags, new object[] { this.DdlLookupFieldTargetField.SelectedValue, false });
                this.cbxAllowMultiValue.Enabled = fieldByInternalName == null;
                this.cbxUnlimitedLengthInDocLib.Enabled = fieldByInternalName == null;
            }
            else
            {
                this.cbxAllowMultiValue.Enabled = false;
                this.cbxUnlimitedLengthInDocLib.Enabled = false;
            }
        }
        protected void DdlLookupFieldTargetList_Changed(object sender, EventArgs e)
        {
            SPWeb contextWeb = SPControl.GetContextWeb(this.Context);
            Guid guid = new Guid(this.DdlLookupFieldTargetList.SelectedValue);
            SPList lookupTolist = contextWeb.Lists[guid];
            PopulateShowFieldDropDown(this.DdlLookupFieldTargetField, lookupTolist, this.OwnerListId, null);
            PopulateShowFieldDropDown(this.CbxlDependentLookupFields, lookupTolist, this.OwnerListId, "");
            this.DisableDependentLookupCheckBoxes();
            bool flag = (lookupTolist != null) && lookupTolist.HasExternalDataSource;
            this.cbxAllowMultiValue.Visible = !flag;
            this.LookupRelationshipsEditor.IsHidden = flag;
            this.LookupRelationshipsEditor.InitializeWithField(this.fldLookup, this.cbxAllowMultiValue.ClientID, true);
            this.Page.SetFocus(this.DdlLookupFieldTargetList);
        }
        protected void RITargetList_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            if ((this.LookupRelationshipsEditor != null) && !this.LookupRelationshipsEditor.IsHidden)
            {
                string selectedValue;
                bool flag;
                if ((this.DdlLookupFieldTargetList != null) && !string.IsNullOrEmpty(this.DdlLookupFieldTargetList.SelectedValue))
                {
                    flag = true;
                    selectedValue = this.DdlLookupFieldTargetList.SelectedValue;
                }
                else
                {
                    flag = false;
                    selectedValue = null;
                }
                e.IsValid = this.LookupRelationshipsEditor.DoesUserHaveRequiredPermissionsOnTargetList(selectedValue, flag);
            }
            else
            {
                e.IsValid = true;
            }
        }
        #endregion
    }
}
